package usersManagement.security;

import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import usersManagement.model.User;
import usersManagement.service.AccessService;

import javax.inject.Inject;

/**
 * User: eluibon
 * Date: 11/12/12
 * Time: 14.13
 * Sample for JPA Realm, currently not used
 */
public class JpaRealm extends AuthenticatingRealm {

    private static final String REALM_NAME = "jpaRealm";

    @Inject private AccessService accessService;

    public JpaRealm() {

        setName(REALM_NAME); //This name must match the name in the User class's getPrincipals() method
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();

        if ((username == null) || (username.equals(""))) {
            throw new AccountException("Null usernames are not allowed by this realm.");
        }

        User user = accessService.findUserByUsername(username);

        if (user == null) {
            throw new UnknownAccountException();
        }

        return new SimpleAuthenticationInfo(username, user.getPassword(), REALM_NAME);
    }
}
